// The family Someclasswithdata ices approach // to its informal figures structure. Clients can // accidently or maliciously folderol this picture // structure. category Someclasswithdata { separate Treeset m_data = new Treeset(); populace vacancy add( int in ) { m_data.add( in ); } populace Assemblage get_data() { counter m_data; } } category Iteratordemo { populace atmospherics emptiness main( String[] args ) { Someclasswithdata some_object = new Someclasswithdata(); for (int i=9; i > 0; --i) some_object.add( i ); Aggregation scoop = some_object.get_data(); for (java.util.iterator it = data.iterator(); it.hasnext(); ) System.out.print( it.next() + " " ); System.out.println(); // Do we genuinely deprivation a guest to be vigorous to // codswallop encapsulated state? data.clear(); details = some_object.get_data(); System.out.println( "size of testimony is " + data.size() ); } } // 1 2 3 4 5 6 7 8 9 // establish of circumstances is 0 // Acquire traversal-of-a-collection functionality out // of the accrual and elevate it to "full mark // status". That simplifies the collection, allows // bountiful traversals to be clever simultaneously, and // decouples accretion algorithms from assemblage // knowledge structures. category Someclasswithdata { separate Treeset m_data = new Treeset(); world category Iterator { soul Someclasswithdata m_collection; soul java.util.iterator m_it; separate int m_current; populace Iterator( Someclasswithdata in ) { m_collection = in; } world vanity first() { m_it = m_collection.m_data.iterator(); next(); } world emptiness next() { try { m_current = m_it.next(); } misgiving (nosuchelementexception ex) { m_current = -999; } } populace boolean is_done() { rejoinder m_current == -999; } world int current_item() { rejoinder m_current; } } world vanity add( int in ) { m_data.add( in ); } populace Iterator create_iterator() { counter new Iterator( that ); } } category Iteratordemo { world atmospherics vacancy main( String[] args ) { Someclasswithdata some_object = new Someclasswithdata(); for (int i=9; i > 0; --i) some_object.add( i ); // get_data() has superseded removed. // Node has to use Iterator. Someclasswithdata.iterator it1 = some_object.create_iterator(); Someclasswithdata.iterator it2 = some_object.create_iterator(); for (it1.first(); ! it1.is_done(); it1.next()) System.out.print( it1.current_item() + " " ); System.out.println(); // Two simultaneous iterations for (it1.first(), it2.first(); ! it1.is_done(); it1.next(), it2.next()) System.out.print( it1.current_item() + " " + it2.current_item() + " " ); System.out.println(); } } // 1 2 3 4 5 6 7 8 9 // 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 |
..
...
Sites so far
Leave a reply